package project.youkumenu.customview;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.support.annotation.Nullable;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.view.View;

/**
 * Created by lgs on 2018/3/8.
 */

public class CustomTextView extends View {

    private String text = "自定义视图";
    private TextPaint textPaint;


    public CustomTextView(Context context) {
        this(context, null);
    }

    public CustomTextView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CustomTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        textPaint = new TextPaint();
        textPaint.setTextSize(18);
        textPaint.setColor(Color.GREEN);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        int text_width = 0;
        int text_height = 0;

        /*
        宽度
         */
        int specMode = MeasureSpec.getMode(widthMeasureSpec);
        int specSize = MeasureSpec.getSize(widthMeasureSpec);
        text_width = specSize;

        specSize = MeasureSpec.getSize(heightMeasureSpec);
        text_height = specSize;

        setMeasuredDimension(text_width, text_height);

    }

    @Override
    protected void onDraw(Canvas canvas) {
        drawText(canvas);
    }

    private void drawText(Canvas canvas) {
        canvas.drawText(text, 0, text.length(), getMeasuredWidth()/2, getMeasuredHeight()/2, textPaint);
    }
}
